package com.atguigu.flink01;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/2/18
 * 以流的形式对有界数据进行处理
 */
public class Flink02_WC_Bound_Stream {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //指定按照批的形式对有界数据进行处理
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
        //TODO 2.从指定的文件中读取数据
        DataStreamSource<String> dataSource = env.readTextFile("D:\\dev\\workspace\\bigdata-0918\\flink-0918\\input\\word.txt");
        //TODO 3.对读取的数据进行切分 封装为二元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> flatDS = dataSource.flatMap(
                new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] words = lineStr.split(" ");
                        for (String word : words) {
                            out.collect(Tuple2.of(word, 1));
                        }
                    }
                }
        );
        //TODO 4.按照单词进行分组
        KeyedStream<Tuple2<String, Integer>, Tuple> keyedDS = flatDS.keyBy(0);
        //TODO 5.求和
        SingleOutputStreamOperator<Tuple2<String, Integer>> sumDS = keyedDS.sum(1);
        //TODO 6.输出
        sumDS.print();
        //TODO 7.执行程序
        env.execute();
    }
}
